﻿using Api.Core.Help;
using Api.Core.IServices.Module;
using Api.Core.IServices.Role;
using Api.Core.IServices.User;
using Api.Core.Model;
using Api.Core.Model.Module;
using Api.Core.Model.Role;
using Api.Core.Model.User;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Api.Core.Controllers
{

    public class RoleController : BaseController
    {
        private readonly IRoleModuleInfoService _roleModuleInfoService;
        private readonly IUserRoleInfoService _userRoleInfoService;
        private readonly IModuleInfoService _moduleInfoService;
        private readonly IRoleInfoService _roleInfoService;
        private readonly IMapper _mapper;

        public RoleController(IRoleInfoService roleInfoService,
            IModuleInfoService moduleInfoService
            , IMapper mapper,
            IUserRoleInfoService userRoleInfoService,
            IRoleModuleInfoService roleModuleInfoService)
        {
            _roleModuleInfoService = roleModuleInfoService;
            _userRoleInfoService = userRoleInfoService;
            _moduleInfoService = moduleInfoService;
            _roleInfoService = roleInfoService;
            _mapper = mapper;
        }

        [HttpPost("roleModule")]
        public async Task<IActionResult> GetModule(RoleDto roleDto = null)
        {
            List<ModuleResponse> moduleResponses = new List<ModuleResponse>();
            var moduleList = await _moduleInfoService.Query();
            var roleList = await _roleInfoService.Query();
            foreach (var item in roleList)
            {
                var roleModule = await _roleModuleInfoService.Query(x => x.RoleId == item.RoleId);
                //if (roleModule.Count == 0) continue;
                var list = roleModule.Select(x => x.ModuleId).ToList();
                var model = moduleList.Where(x => list.Contains(x.Id)).ToList();
                var modelDto = MenuEntityToDto.GetTreeApi(model);
                moduleResponses.Add(new ModuleResponse()
                {
                    RoleId = item.RoleId,
                    RoleName = item.RoleName,
                    Children = modelDto
                });
            }
            var data = moduleResponses.Take(roleDto.pageSize * roleDto.pageIndex).Skip(roleDto.pageSize * (roleDto.pageIndex - 1)).ToList();

            var totalCount = moduleResponses.Count();
            int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / roleDto.pageSize.ObjToDecimal())).ObjToInt();

            var page = new PageModel<ModuleResponse>()
            {
                page = roleDto.pageIndex,
                pageCount = pageCount,
                dataCount = totalCount,
                PageSize = roleDto.pageSize,
                Children = data

            };
            return Ok(page);
        }

        [HttpGet("roleAll")]
        public async Task<IActionResult> GetAll()
        {
            var roleModel = await _roleInfoService.Query();
            return Ok(roleModel);
        }

        [HttpPost("role")]
        public async Task<IActionResult> Get(RoleDto roleDto = null)
        {
            var roleModel = await _roleInfoService.GetRole(roleDto);
            return Ok(roleModel);
        }

        [HttpGet("roleId")]
        public async Task<RoleDto> GetById(int Id)
        {
            var roleModel = await _roleInfoService.Query(x => x.RoleId == Id);
            var role = _mapper.Map<RoleEntity, RoleDto>(roleModel.FirstOrDefault());
            return role;
        }


        [HttpPost("updateRole")]
        public async Task<IActionResult> UpdateRole(RoleDto roleDto)
        {
            var info = await _roleInfoService.Query(x => x.RoleId == roleDto.RoleId);
            var role = info.FirstOrDefault();
            _mapper.Map(roleDto, role);
            var isTrue = await _roleInfoService.Update(role);
            return new JsonResult(new
            {
                sussess = isTrue
            });
        }

        [HttpPost("updateUserRole")]
        public async Task<IActionResult> UpdateUserRole([FromQuery]string userId, int roleId)
        {
            var isTrue = false;
            var userRole = await _userRoleInfoService.Query(x => x.UserID == userId);
            var model = userRole.FirstOrDefault();
            if (model == null)
            {
                model = new UserRoleEntity() { UserID = userId, RoleId = roleId };
                isTrue = await _userRoleInfoService.Add(model) >= 0;
            }
            else
            {
                model.RoleId = roleId;
                isTrue = await _userRoleInfoService.Update(model);
            }
            return new JsonResult(new
            {
                sussess = isTrue
            });
        }


        [HttpPost("CreatRole")]
        public async Task<IActionResult> AddRole(RoleDto roleDto)
        {
            var role = _mapper.Map<RoleDto, RoleEntity>(roleDto);
            var isTrue = await _roleInfoService.Add(role);
            return new JsonResult(new
            {
                sussess = isTrue != -1 ? true : false
            });
        }


        [HttpPost("DelRole")]
        public async Task<IActionResult> DelRole(RoleDto roleDto)
        {
            var isTrue = await _roleInfoService.DeleteById(roleDto.RoleId);
            return new JsonResult(new
            {
                sussess = isTrue
            });
        }
    }
}